package univ.bme.accounting.beans;


import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;

import univ.bme.accounting.dao.UserDAO;
import univ.bme.accounting.domain.User;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor

@ManagedBean
@RequestScoped
public class UserMB extends MBUtils {

	@EJB
	private UserDAO userdao;

	@ManagedProperty("#{accountingSessionBean}")
	private AccountingSessionBean accountingSessionBean;
	
	private User user;

	//For registration
	public User getUser() {
		if(user == null){
			user = new User();
		}
		return user;
	}
	
	//This is used to get the user instance for the actual request, for the user's own pages
	//the user variable was not set, and the session user is used
	public User getCurrentRequestUser() {
		//This validates the visibility again
		if(user == null || 
			(user.getVisible().equals(User.NON_PUBLIC_DATA) && !accountingSessionBean.isUserAdmin())){
			return accountingSessionBean.getUser();
		}
		return user;
	}
	
	//Rendering private parts of the pages
	public boolean isThisRequestForMe(){
		return accountingSessionBean.getUser().equals(getCurrentRequestUser());
	}
	
	//Captcha validation
	public void submit(ActionEvent event) {
		sendErrorMessageToUser("Correct");
    }
	
	public String registerUser(){
		try {
			if(!user.getPassword().equals(getRequest().getParameter("register:passwordconfirm"))){
				sendErrorMessageToUser(bundle.getString("passwordsNotEqual"));
				return null;
			}
			
			if(userdao.findUserByUsername(user.getUsername()) != null){
				sendErrorMessageToUser(bundle.getString("reservedUsername"));
				return null;
			}
				
			user.setRole(User.USER_ROLE);
			user.setVisible(User.NON_PUBLIC_DATA);
			user.setPassword(getSha256(user.getPassword()));
			userdao.save(user);
		} catch (EJBException e) {
			sendErrorMessageToUser(bundle.getString("allrequired"));
			return null;
		} catch (NoSuchAlgorithmException e) {
			sendErrorMessageToUser(bundle.getString("operationFailed"));
			return null;
		}
		
		sendInfoMessageToUser(bundle.getString("operationCompleted"));
		return "logout";
	}
	
	public String updateUser(){
		try {
			String new_password = getRequest().getParameter("userupdate:new_password");
			String new_password_confirm = getRequest().getParameter("userupdate:new_password_confirm");
			if(!new_password.isEmpty())
			{
				if(!new_password.equals(new_password_confirm)){
					sendErrorMessageToUser("");
					return null;
				}
				accountingSessionBean.getUser().setPassword(getSha256(new_password));
			}
			
			userdao.update(accountingSessionBean.getUser());
		} catch (EJBException e) {
			sendErrorMessageToUser(bundle.getString("allrequired"));
			return null;
		} catch (NoSuchAlgorithmException e) {
			sendErrorMessageToUser(bundle.getString("operationFailed"));
			return null;
		}
		
		sendInfoMessageToUser(bundle.getString("operationCompleted"));
		return "home";
	}
	
	public List<User> getPublicUsers() {
		return userdao.findPublicUsers();
	}
	
	public String deleteCurrentUser() throws IOException{
		try {
			userdao.delete(accountingSessionBean.getUser());
		} catch (EJBException e) {
			sendErrorMessageToUser("Error!");
			return null;
		}
		
		return  accountingSessionBean.logOut();
	}
	
	/// -------- Administrator functions -----------
	public List<User> getAllUsers() {
		return userdao.findAll();
	}

	public String deleteUser(){
		try {
			userdao.delete(user);
		} catch (EJBException e) {
			sendErrorMessageToUser(bundle.getString("operationFailed"));
			return null;
		}			
		
		sendInfoMessageToUser(bundle.getString("operationCompleted"));
		
		return "admin_page?faces-redirect=true";
	}
	
	public String goToTransactions(){
		return "/pages/protected/user/listTransactions.xhtml?userid="+user.getId()+"&faces-redirect=true";
	}
}